package com.biostime.qdingding.modules.qd.promotions;

import java.util.Arrays;
import java.util.List;

import com.biostime.qdingding.common.utils.SpringContextHolder;
import com.biostime.qdingding.common.utils.StringUtils;
import com.biostime.qdingding.modules.qd.entity.Contract;
import com.biostime.qdingding.modules.qd.entity.Course;
import com.biostime.qdingding.modules.qd.entity.Promotion;
import com.biostime.qdingding.modules.qd.service.ContractService;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 折扣优惠
 * @author phil
 * @version 2015-11-20
 */
public class MemberDiscountor implements Discountor {
	
	public static final String Formula = "MemberDiscountor";
	
	public MemberDiscountor(){
		contractService = SpringContextHolder.getBean(ContractService.class);
	}
	
	private ContractService contractService;

	@Override
	public void discount(Discountable discountable) {
		if(support(discountable)){
			System.out.println("折扣优惠");
			
			Course course = (Course)discountable;
			Promotion promotion = course.getPromotions().get(Formula);
			
			//第一步：获取合同额
			Contract contract = contractService.getByStudentId(course.getStudentId());
			
			//第二步：根据合同额确定折扣
			double discount = 10.0d;
			String promotionName = "";
			if(contract!=null){
				ObjectMapper mapper = new ObjectMapper();
				List<MemberDiscountor.Arg> args = null;
				try {
					args = Arrays.asList(mapper.readValue(promotion.getArgValue(), MemberDiscountor.Arg[].class));
				}catch(Exception ex){
					ex.printStackTrace();
				}
				
				if(args != null && args.size()>0){
					for(MemberDiscountor.Arg arg : args){
						double level = StringUtils.toDouble(arg.getLevel());
						if(level == contract.getAmount()){
							discount = arg.discount;
							promotionName = String.format("%s%s折", arg.levelName, arg.discount);
						}
					}
				}
			}
			
			//第三步：求出折扣价格
			promotion.setPreMoney(course.getPriceNow());
			promotion.setMoney(course.getPriceNow()*(10-discount)*0.1);
			promotion.setPromotionName(promotionName);
			course.setPriceNow(course.getPriceNow()*discount*0.1);
		}else{
			System.out.println("折扣优惠 ( Not Support )!");
		}
	}

	@Override
	public boolean support(Discountable discountable) {
		Course course = (Course)discountable;
		
		return course.getPromotions().containsKey(Formula);
	}
	
	/**
	 * 配置参数类
	 * @author phil
	 * @version 2015-11-20
	 */
	public static class Arg{
		
		private String level; //折扣额度
		private String levelName; //等级名称
		private double discount; //折扣
		
		public String getLevel() {
			return level;
		}
		public void setLevel(String level) {
			this.level = level;
		}
		
		public double getDiscount() {
			return discount;
		}
		public void setDiscount(double discount) {
			this.discount = discount;
		}
		
		public String getLevelName() {
			return levelName;
		}
		public void setLevelName(String levelName) {
			this.levelName = levelName;
		}
	}
}
